import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;

import javax.net.ssl.HttpsURLConnection;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.net.*;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

public class HttpClient
{
  private URL url;
  private int connectionTimeout;
  private int readTimeOut;
  private String result;

  public String getResult()
  {
    return this.result;
  }

  public void setResult(String result)
  {
    this.result = result;
  }

  public HttpClient(String url, int connectionTimeout, int readTimeOut)
  {
    try
    {
      this.url = new URL(url);
      this.connectionTimeout = connectionTimeout;
      this.readTimeOut = readTimeOut;
    } catch (MalformedURLException e) {
      e.printStackTrace();
    }
  }

  public int send(String message, String encoding)
    throws Exception
  {
    try
    {
      HttpURLConnection httpURLConnection = createConnection(encoding);
      if (httpURLConnection == null) {
        throw new Exception("��������ʧ��");
      }
      requestServer(httpURLConnection, message, 
        encoding);
      this.result = response(httpURLConnection, encoding);
      return httpURLConnection.getResponseCode();
    } catch (Exception e) {
      throw e;
    }
  }

  private void requestServer(URLConnection connection, String message, String encoder)
    throws Exception
  {
    PrintStream out = null;
    try {
      connection.connect();
      out = new PrintStream(connection.getOutputStream(), false, encoder);
      out.print(message);
      out.flush();
    }
    catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (out != null)
        out.close();
    }
  }

  private String response(HttpURLConnection connection, String encoding)
    throws URISyntaxException, IOException, Exception
  {
    InputStream in = null;
    StringBuilder sb = new StringBuilder(1024);
    try {
      if (200 == connection.getResponseCode()) {
        in = connection.getInputStream();
        sb.append(IOUtils.toString(in, encoding));
      } else {
        in = connection.getErrorStream();
        sb.append(IOUtils.toString(in, encoding));
      }
      return sb.toString();
    } catch (Exception e) {
      throw e;
    }
    finally {
      if (in != null) {
        in.close();
      }
      if (connection != null)
        connection.disconnect();
    }
  }

  private HttpURLConnection createConnection(String encoding)
    throws ProtocolException
  {
    HttpURLConnection httpURLConnection = null;
    try {
      httpURLConnection = (HttpURLConnection)this.url.openConnection();
    } catch (IOException e) {
      e.printStackTrace();
      return null;
    }
    httpURLConnection.setConnectTimeout(this.connectionTimeout);
    httpURLConnection.setReadTimeout(this.readTimeOut);
    httpURLConnection.setDoInput(true);
    httpURLConnection.setDoOutput(true);
    httpURLConnection.setUseCaches(false);
    httpURLConnection.setRequestProperty("Content-type", 
      "application/json;charset=" + encoding);
    httpURLConnection.setRequestMethod("POST");
    if ("https".equalsIgnoreCase(this.url.getProtocol())) {
      HttpsURLConnection husn = (HttpsURLConnection)httpURLConnection;
//      husn.setSSLSocketFactory(new BaseHttpSSLSocketFactory());

      return husn;
    }
    return httpURLConnection;
  }

  private String getRequestParamString(Map<String, String> requestParam, String coder)
  {
    if ((coder == null) || ("".equals(coder))) {
      coder = "UTF-8";
    }
    StringBuffer sf = new StringBuffer("");
    String reqstr = "";
    if ((requestParam != null) && (requestParam.size() != 0)) {
      for (Entry en : requestParam.entrySet()) {
        try {
          sf.append((String)en.getKey() + 
            "=" + (
            (en.getValue() == null) || ("".equals(en.getValue())) ? "" : 
            URLEncoder.encode((String)en.getValue(), coder)) + "&");
        } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
          return "";
        }
      }
      reqstr = sf.substring(0, sf.length() - 1);
    }
    return reqstr;
  }

  public int sendGetRequest() {
    HttpURLConnection connection = null;
    try {
      connection = (HttpURLConnection)this.url.openConnection();
      connection.setDoOutput(true);
      connection.setDoInput(true);
      connection.setRequestMethod("GET");
      connection.setUseCaches(false);
      connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      connection.connect();
      this.result = response(connection, "UTF-8");
      return connection.getResponseCode();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return 0;
  }
  
	public static void main(String[] args) throws Exception {
		Map<String, String> dataMap =new TreeMap<String,String>();
		dataMap.put("webOrderId","17121111400684002044lqkrevl");					
        dataMap.put("inTradeOrderNo", "20171209144416333");
        dataMap.put("unionOrderNo", "20171211145698471216");
        dataMap.put("tradeStatus", "SUCCESS");
        dataMap.put("gmtCreate","20171211114006");
        dataMap.put("gmtPayment", "20171211113705");
        dataMap.put("totalFee", "1");
        dataMap.put("productDescription", "0001|0");
        dataMap.put("signMsg", "65601C77E5893EC3BDC3C2BD45D92940");
        
        JSONObject jsonsend = JSONObject.fromObject(dataMap);
        
        HttpClient post = new HttpClient("http://183.239.128.110:8449/UnionPay/notify", 30000, 30000);
        
        post.send(jsonsend.toString(), "UTF-8");
        
        String result = post.getResult();
        
        System.out.println(result);
	}
  
  
}